package com.zj.easywebview

import android.content.Context
import com.zj.easywebview.util.CommonUtil.getPackageName
import org.json.JSONObject
import android.content.Intent
import android.widget.Toast
import android.os.Bundle
import java.lang.Boolean
import java.lang.Exception

/**
 * @author zhengjun
 * @desc js交互跳转方法统一封装参数处理
 * @create at 2018/8/13 14:34
 */
object JsMethosManager {
    private const val CLASS_PATH = "clsPath"
    /**
     * @desc js打开指定activity
     * @author zhengjun
     * @created at 2018/7/26 10:40
     */
    fun openActivity(context: Context, data: JSONObject) {
        try {
            startActivityForResult(context, data)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun startActivityForResult(context: Context, jsonObject: JSONObject) {
        try {
            val intent = fillIntentParams(context, jsonObject)
            context.startActivity(intent)
        } catch (e: Exception) {
            Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }

    /**
     * @desc 构造跳转传值的intent
     * @author zhengjun
     * @created at 2018/9/4 16:52
     */
    private fun fillIntentParams(context: Context, jo: JSONObject): Intent? {
        var intent: Intent? = null
        try {
            val clsPath = String.format("%s%s", getPackageName(context), jo.optString(CLASS_PATH))
            intent = Intent()
            intent.setClass(context, Class.forName(clsPath))
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            val bundle = Bundle()
            val it: Iterator<*> = jo.keys()
            while (it.hasNext()) {
                val key = it.next().toString()
                val value = jo.optString(key)
                if ("true" == value || "false" == value) {
                    bundle.putBoolean(key, Boolean.valueOf(value))
                    continue
                }
                try {
                    if ("position" == key) {
                        bundle.putInt(key, value.toInt())
                    } else {
                        bundle.putString(key, value)
                    }
                } catch (e: Exception) {
                    bundle.putString(key, value)
                }
            }
            intent.putExtras(bundle)
        } catch (e: ClassNotFoundException) {
            Toast.makeText(context, "请升级到最新版本后重试", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
        return intent
    }
}